package com.ctshk.rpc.bus.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsValidCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.enums.bus.BusConst;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.req.MainTreeData;
import com.ctshk.common.req.OperationByIdReq;
import com.ctshk.common.req.OperationByLikeReq;
import com.ctshk.common.service.support.BaseService;
import com.ctshk.common.utils.Assist;
import com.ctshk.common.utils.BConst;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.HktOrderUtil;
import com.ctshk.common.utils.RlgOrderUtil;
import com.ctshk.rpc.bus.dto.BusStopsDTO;
import com.ctshk.rpc.bus.dto.Constants;
import com.ctshk.rpc.bus.entity.BusStops;
import com.ctshk.rpc.bus.mapper.BusStopsMapper;
import com.ctshk.rpc.bus.req.BusStopsDictListQueryReq;
import com.ctshk.rpc.bus.req.BusStopsPassDictListQueryReq;
import com.ctshk.rpc.bus.req.BusStopsQueryReq;
import com.ctshk.rpc.bus.req.BusStopsSaveReq;
import com.ctshk.rpc.bus.service.IBusStopsService;

/**
 * <p>
 * 巴士站点表 服务实现类
 * </p>
 *
 * @author 彭柳霖
 * @since 2021-02-08
 */
@DubboService
public class BusStopsServiceImpl extends ServiceImpl<BusStopsMapper, BusStops> implements IBusStopsService, BaseService {

    @Autowired
    private BusStopsMapper busStopsMapper;

    /**
     * 查询所有巴士站点列表
     * @return
     */
    @Override
    public List<BusStopsDTO> queyList() {
        List<BusStops> busStopsList = busStopsMapper.selectList(new QueryWrapper<BusStops>().lambda().eq(BusStops::getIsDeleted, Constants.NOT_DELETE));
        List<BusStopsDTO> busStopsDTOList = EntityUtil.copyList(busStopsList, BusStopsDTO.class);
        return busStopsDTOList;
    }

    /**
     *  获取中汽API所有站点信息入库
     */
    @Override
    @Async
    public Result importHktBusStop() throws Exception {
        //通过API接口获取中港通数据
        List<Map<String, Object>> list = HktOrderUtil.getLocations();
        if(CollectionUtils.isEmpty(list)){
            return Result.failed(SystemError.SYS_411);
        }
        batchsaveHktBusStopInfo(list);
        return Result.success();
    }



    /**
     * 中汽API站点导入
     * @return
     * @throws Exception
     */
    @Override
    @Async
    public Result importRglBusStop() throws Exception {
        //通过API接口获取中港通数据
    	List<Map<String, Object>> list = RlgOrderUtil.getstopStaionList();
        if(CollectionUtils.isEmpty(list)){
            return Result.failed(SystemError.SYS_411);
        }
        batchsaveRglBusStopInfo(list);
        return Result.success();
    }


    /**
     * 中港通巴士站点保存
     * @param mapList
     */
    public int batchsaveHktBusStopInfo(List<Map<String, Object>> mapList) throws Exception {
        if(CollectionUtils.isEmpty(mapList)){
            return -1;
        }
        
        //路由站点信息，格式：城市名称_站点名称
        Set<String> routeInfoList = Assist.defaultSet(busStopsMapper.queryRouteInfoList());
        
        for(Map<String, Object> resultMap : mapList){
        	//出发城市
        	String toCityName = (String) resultMap.get("toCityName");
        	//到达城市
        	String fromCityName = (String) resultMap.get("fromCityName");
        	//出发城市ID
        	String toCityId = (String) resultMap.get("toCityId");
        	//到达城市ID
        	String fromCityId = (String) resultMap.get("fromCityId");
        	//出发站点ID列表
        	List<String> fromStationIdList = Assist.defaultList(Assist.splitToList(resultMap.get("fromStations"), "-"));
        	//到达站点ID列表
        	List<String> toStationIdList = Assist.defaultList(Assist.splitToList(resultMap.get("toStations"), "-"));
        	
        	if (Assist.isBlank(toCityName) || Assist.isBlank(fromCityName)) {
        		continue;
        	}
        	
        	//站点列表
        	List<Map> stopsMapList = (List<Map>) resultMap.get("stopsMap");
        	if (Assist.isNotEmpty(stopsMapList)) {
        		//key：站点ID；value：站点数据
        		Map<String, Map> stopsIdMap = new HashMap<>();
        		for (Map map : stopsMapList) {
        			String stopsId = (String)map.get("id");
        			String stopsName = (String)map.get("name");
        			if (Assist.isBlank(stopsId) || Assist.isBlank(stopsName)) {
        				continue;
        			}
        			stopsIdMap.put(stopsId, map);
        		}
        		
        		//出发站点
        		for (String fromStationId : fromStationIdList) {
					batchsaveHktBusStopInfoCityInfo(stopsIdMap, fromStationId, fromCityId, fromCityName, routeInfoList);
				}
        		
        		//到达站点
        		for (String toStationId : toStationIdList) {
        			batchsaveHktBusStopInfoCityInfo(stopsIdMap, toStationId, toCityId, toCityName, routeInfoList);
				}
        	}

        }
        return 0;
    }
    
    /**
     * 中港通巴士站点保存，城市相关逻辑
     * @param stopsName
     * @param cityName
     * @param routeInfoList
     */
    private void batchsaveHktBusStopInfoCityInfo(Map<String, Map> stopsIdMap, String stopsId, String cityId, String cityName, Set<String> routeInfoList) {
    	if (Assist.isBlank(stopsId)) {
			return;
		}
		
		Map stopsMap = stopsIdMap.get(stopsId);
		if (stopsMap == null) {
			return;
		}
		
    	String stopsName = (String) stopsMap.get("name");
    	if (Assist.isBlank(cityName)) {
			return;
		}
		
		String curRouteInfo = cityName + "_" + stopsName;
		
		//已包含此站点，则不再更新
		if (routeInfoList.contains(curRouteInfo)) {
			return;
		}
		
		BusStops entity = newCreateEntity(BusStops.class);
		//暂时做法，后面映射到主数据的城市ID
		entity.setCityId(Assist.toLong(cityId));
		entity.setThirdCityCode(cityId);
		entity.setBusCompaniesId(BusConst.COMPANIES_ID_HKT);
		entity.setBusCompaniesName(BusConst.COMPANIES_NAME_HKT);
		entity.setSupplierId(BusConst.SUPPLIER_ID_HKT);
		entity.setSupplierName(BusConst.SUPPLIER_NAME_HKT);
		entity.setCityName(cityName);
		entity.setSiteName(stopsName);
		entity.setStatus(BConst.ZERO);
		entity.setIsApi(BConst.ONE);
		busStopsMapper.insert(entity);
		
		routeInfoList.add(curRouteInfo);
	}
    
    /**
     * 中汽城市ID转换
     * @return
     */
    private Long rglTranCityId(String cityCode) {
		if (Assist.isBlank(cityCode)) {
			return null;
		}
		
		cityCode = (int) cityCode.charAt(0) + cityCode.substring(1);
		return Assist.toLong(cityCode);
	}
    

    /**
     * 中汽巴士站点保存
     * @param mapList
     */
    public int batchsaveRglBusStopInfo(List<Map<String, Object>> mapList) throws Exception {
        if(CollectionUtils.isEmpty(mapList)){
            return -1;
        }
        
        //路由站点信息，格式：城市名称_站点名称
        Set<String> routeInfoList = Assist.defaultSet(busStopsMapper.queryRouteInfoList());
        
        for (Map<String, Object> resultMap : mapList) {
        	String cityName = (String) resultMap.get("cityName");
        	String cityCode = (String) resultMap.get("cityCode");
        	List<Map> dataMapList = (List<Map>) resultMap.get("stationList");
        	
        	if (Assist.isBlank(cityName) || Assist.isEmpty(dataMapList)) {
        		continue;
        	}
        	
        	for(Map map : dataMapList){
        		String stopsName = (String)map.get("StationName");
        		if (Assist.isBlank(stopsName)) {
        			continue;
        		}
        		
        		String curRouteInfo = cityName + "_" + stopsName;
        		
        		//已包含此站点，则不再更新
        		if (routeInfoList.contains(curRouteInfo)) {
        			continue;
        		}
        		
        		BusStops entity = newCreateEntity(BusStops.class);
        		//暂时做法，后面映射到主数据的城市ID
        		entity.setCityId(rglTranCityId(cityCode));
        		entity.setThirdCityCode(cityCode);
        		entity.setBusCompaniesId(BusConst.COMPANIES_ID_RGL);
        		entity.setBusCompaniesName(BusConst.COMPANIES_NAME_RGL);
        		entity.setSupplierId(BusConst.SUPPLIER_ID_RGL);
        		entity.setSupplierName(BusConst.SUPPLIER_NAME_RGL);
        		entity.setCityName(cityName);
        		entity.setSiteName(stopsName);
        		entity.setStatus(BConst.ZERO);
        		entity.setIsApi(BConst.ONE);
        		busStopsMapper.insert(entity);
        		
        		routeInfoList.add(curRouteInfo);
        	}
		}
        
//        for(Map map : mapList){
//            Long id = Long.valueOf((String)map.get("StationCode"));
//            String name = (String)map.get("StationName");
//            BusStops busStops = busStopsMapper.selectById(id);
//            if(Objects.isNull(busStops)){
//                busStops = new BusStops();
//                busStops.setId(id);
//                busStops.setSiteName(name);
//                busStops.setStatus(IsValidCode.VALID.getCode());
//                busStops.setCreateId(1111L);
//                busStops.setGmtCreate(LocalDateTime.now());
//                busStops.setIsDeleted(IsDeletedCode.NO.getCode());
////                busStopsMapper.insert(busStops);
//            }else{
//                busStops.setSiteName(name);
//                busStops.setGmtModified(LocalDateTime.now());
//                busStops.setModifiedId(1111L);
////                busStopsMapper.updateById(busStops);
//            }
//
//        }
        return 0;
    }
    
    /**
     * 查询巴士站点列表
     */
    @Override
    public Result<PageResponse<BusStopsDTO>> queryStopsList(BusStopsQueryReq req) {
    	IPage<BusStopsDTO> page = busStopsMapper.queryStopsList(req);
    	return newPageResult(page);
    }
    
    /**
     * 保存巴士站点
     */
    @Transactional
    @Override
    public Result<Void> saveStops(BusStopsSaveReq req, TokenUser tokenUser) {
    	//新增
    	if (Assist.isNull(req.getId())) {
    		BusStops entity = newCreateEntity(BusStops.class, req, tokenUser);
    		entity.setStatus(IsValidCode.VALID.getCode());
    		busStopsMapper.insert(entity);
    	} else {  //修改
    		BusStops entity = newUpdateEntity(BusStops.class, req, tokenUser);
    		busStopsMapper.assertUpdateById(entity);
		}
    	return newResult();
    }
    
    /**
     * 删除巴士站点
     */
    @Transactional
    @Override
    public Result<Void> deleteStops(OperationByIdReq req, TokenUser tokenUser) {
    	busStopsMapper.deleteById(req.getId());
    	return newResult();
    }
    
    /**
     * 启用/禁用巴士站点
     */
    @Transactional
    @Override
    public Result<Void> changeStopsStatus(OperationByIdReq req, TokenUser tokenUser) {
    	BusStops entity = busStopsMapper.assertExistById(req.getId());
    	
    	if (entity.getStatus() == null || BConst.ONE.equals(entity.getStatus())) {
    		entity.setStatus(BConst.ZERO);
    	} else {
    		entity.setStatus(BConst.ONE);
		}
    	fillUpdateEntity(entity, tokenUser);
    	
    	busStopsMapper.updateById(entity);
    	
    	return newResult();
    }
    
    /**
     * 查询巴士站点数据字典列表
     * @param req
     * @return
     */
    @Override
    public Result<PageResponse<MainTreeData>> queryStopsDictList(BusStopsDictListQueryReq req) {
    	IPage<MainTreeData> page = busStopsMapper.queryStopsDictList(newPage(req), req);
    	return newPageResult(page);
    }
    
    /**
     * 查询巴士经停站站点数据字典列表
     * @param req
     * @return
     */
    @Override
    public Result<PageResponse<MainTreeData>> queryStopsPassDictList(BusStopsPassDictListQueryReq req) {
    	IPage<MainTreeData> page = busStopsMapper.queryStopsPassDictList(newPage(req), req);
    	return newPageResult(page);
    }
    
    /**
     * 检索巴士城市列表
     * @param req
     * @return
     */
    @Override
    public Result<PageResponse<MainTreeData>> searchCityList(OperationByLikeReq req) {
    	IPage<MainTreeData> page = busStopsMapper.searchCityList(newPage(req), req);
    	return newPageResult(page);
    }
}
